<?php

/**
 * @author Gideon Amissah<kuulmek@yahoo.com>
 */
class QuestionsController extends AppController {

    var $name = 'Questions';
    var $helpers = array('Form', 'Html', 'Session');
    var $components = array('RequestHandler', 'Session', 'Email', 'Pdf');
    var $layout = 'app_layout';

    # Models to be used
    var $uses = array(
        'Question',
        'Answer',
        'ClientScore',
        'Info',
        'TempScore',
        'BioData'
    );

    # Controller Actions

    function index() {
        /** Process Post Survey * */
        if (count($_POST) > 0) {
            $post_data = $_POST['data'];
            if ($this->Session->check('QuesAns')) {
                $ques_ans = $this->Session->read('QuesAns');
                foreach ($post_data as $ques_id => $val) {
                    $group_arr = $this->__get_question_group($ques_id);
                    $group = $group_arr['Question']['question_group'];

                    if (isset($ques_ans[$group][$ques_id])) { //Check if the question id is in the session
                        $ques_ans[$group][$ques_id] = null; // Clear it
                        $ques_ans[$group][$ques_id] = $val; // Fill with new set of Answers
                    } else { // Just add the quetion and answer set
                        $ques_ans[$group][$ques_id] = $val; // Fill with new set of Answers
                    }
                }
                // Overwrite the session for this new data
                $this->Session->write('QuesAns', $ques_ans);
            } else {
                foreach ($post_data as $ques_id => $val) {
                    $group_arr = $this->__get_question_group($ques_id);
                    $group = $group_arr['Question']['question_group'];
                    $ques_ans = array();
                    $ques_ans[$group] = $post_data;
                }
                $this->Session->write('QuesAns', $ques_ans);
            }
            
        }


        //On the last page and the next question set buttom is clicked
        $show_intro = false;
        if ($this->Session->check('ShowIntro')) {
            if($this->Session->read('ShowIntro')){
                $show_intro = true;
                $this->Session->delete('ShowIntro');
            }
        }

        
        if (isset($_GET['nextQuesSet'])) {
            $this->Session->delete('QuesGroupType');
            $show_intro = true;
        }

        // get all the questions group if not set already
        $continue = true;
        if ($this->Session->check('QuesGroupType')) {
            $ques_group_type = $this->Session->read('QuesGroupType');

            $arr = $this->Session->read('QuesGroup');
            if (count($arr) > 0) {
                $continue = true;
            } else {
                $continue = false;
            }
        }
        else {
            $arr = $this->Session->read('QuesGroup');
            if (count($arr) > 0) {
                $ques_group_type = array_shift($arr);
                $this->Session->write('QuesGroupType', $ques_group_type);
                $this->Session->write('QuesGroup', $arr);

                $continue = true;
            } else {
                $continue = false;
            }
        }


        if (isset($_GET['finish'])) {
            $this->__processSurvey();
            /** Redirect to Statistics page * */
            $this->redirect(array('controller' => 'Questions', 'action' => 'personalInfo'));
        }

        /** Pagination * */
        $maxRows_display = 3;
        $pageNum_display = 0;
        $totalRows_display = 0;

        if (isset($_GET['pageNum_display'])) {
            $pageNum_display = $_GET['pageNum_display'];
        } else {
            if ($this->Session->check('Page')) {
                $pageNum_display = $this->Session->read('Page');
            }
        }

        $startRow_display = $pageNum_display * $maxRows_display;

        $questions_set = $this->Question->find('all', array(
            'contain' => array('Answer'),
            'conditions' => array('Question.question_group' => $ques_group_type),
            'limit' => "$startRow_display, $maxRows_display",
            'recursive' => 1
                ));

        if (isset($_GET['totalRows_display'])) {
            $totalRows_display = $_GET['totalRows_display'];
        } else {
            $totalRows_display = $this->Question->find('count', array(
                'conditions' => array('Question.question_group' => $ques_group_type),
                'recursive' => -1
                    ));
        }

        $totalPages_display = ceil($totalRows_display / $maxRows_display) - 1;

        $queryString_display = "";
        $queryString_display = sprintf("&totalRows_display=%d%s", $totalRows_display, $queryString_display);


        if ($ques_group_type == 'p') {
            $header = "Section A: The People Factor";
        } else if ($ques_group_type == 'sys') {
            $header = "Section B: The System Factor";
        } else if ($ques_group_type == 'str') {
            $header = "Setion C: The Strategy Factor";
        }

        //save clients session states to db
        $this->__saveClientScoreSession();

        /** Pagination Ends * */
        $this->set(compact('ques_group_type','continue', 'questions_set', 'maxRows_display', 'pageNum_display', 'totalRows_display', 'startRow_display', 'totalPages_display', 'queryString_display', 'header','show_intro'));
    }

    function __saveClientScoreSession() {
        $data = array();
        $ques_ans = $this->Session->read('QuesAns');
        $info_id = $this->Session->read('Client_id');
        $client_data = $this->Session->read('Client_data');
        $ques_group = $this->Session->read('QuesGroup');
        $ques_group_type = $this->Session->read('QuesGroupType');

        $client_temp_score = $this->TempScore->find('first', array(
            'fields' => array('id'),
            'conditions' => array('info_id' => $info_id),
            'recursive' => -1
                ));

        $id = isset($client_temp_score['TempScore']['id']) ? $client_temp_score['TempScore']['id'] : 0;

        if (isset($_GET['pageNum_display'])) {
            $page = $_GET['pageNum_display'];
        } elseif (isset($client_data['TempScore']['page'])) {
            $page = $client_data['TempScore']['page'];
        } else {
            $page = 0;
        }

        $this->TempScore->id = $id;
        $data['TempScore'] = array(
            'info_id' => $info_id,
            'question_score' => serialize($ques_ans),
            'page' => $page,
            'ques_group' => serialize($ques_group),
            'ques_group_type' => $ques_group_type
        );

        $this->TempScore->save($data);

        return;
    }

    function __get_question_group($ques_id) {
        return $this->Question->find('first', array(
                    'fields' => array('Question.id', 'Question.question_group'),
                    'conditions' => array('Question.id' => $ques_id),
                    'recursive' => -1
                ));
    }

    /**
     * Display  the question instructions
     */
    function instructions() {
        $this->Session->delete('QuesAns');
        $this->Session->delete('QuesGroup');
        $this->Session->delete('QuesGroupType');
        $this->Session->delete('Page');
        $this->Session->delete('ShowIntro');

        $info_id = $this->Session->read('Client_id');

        $t = $this->TempScore->find('first', array(
            'conditions' => array('TempScore.info_id' => $info_id),
            'recursive' => -1
        ));

        if ($t) { //check for member saved session if any
            $this->Session->write('QuesAns', unserialize($t['TempScore']['question_score']));
            $this->Session->write('QuesGroup', unserialize($t['TempScore']['ques_group']));
            $this->Session->write('QuesGroupType', $t['TempScore']['ques_group_type']);
            $this->Session->write('Page', $t['TempScore']['page']);

            $this->Session->write('ShowIntro', false);
        }
        else {
            // get all the questions group if not set already
            $ques_group_set = Set::combine($this->Question->find('all', array(
                'fields' => array('id', 'question_group'),
                'group' => "Question.question_group",
                'recursive' => -1
            )), '{n}.Question.id', '{n}.Question');

            ksort($ques_group_set);

            $arr = array();
            foreach ($ques_group_set as $d) {
                $arr[] = $d['question_group'];
            }

            $this->Session->write('QuesGroup', $arr);
            $this->Session->write('ShowIntro', true);
        }
    }

    function __processSurvey() {
        $data = array();
        $ques_ans = $this->Session->read('QuesAns');
        $info_id = $this->Session->read('Client_id');
        $count = 0;
        $save_str = '';
        foreach ($ques_ans as $que_grp => $value_que_ans) {
            $question_score_str = '';
            foreach ($value_que_ans as $que_id => $anss) {
                if (is_array($anss) || is_numeric($anss)) {
                    $questions_set = $this->Question->find('first', array(
                        'fields' => array('Question.id', 'Question.question_code', 'Question.type', 'Question.score_type'),
                        'conditions' => array('Question.id' => $que_id),
                        'contain' => array('Answer' => array(
                                'conditions' => array('Answer.id' => $anss),
                                'fields' => array('SUM(Answer.score) as score')
                        )),
                        'recursive' => 1
                            ));

                    if ($questions_set['Question']['type'] == 'checkbox') {
                        $score_type = $questions_set['Question']['score_type'];
                        if ($score_type) {
                            $no_answers = count($anss);
                            $conditions_score_array = explode(',', $score_type);
                            foreach ($conditions_score_array as $key => $value) {
                                $conditions_score_pair = explode(':', $value);
                                $conditions_str = $conditions_score_pair[0];
                                $score = $conditions_score_pair[1];
                                $conditions_array = explode(';', $conditions_str);
                                $condition = $conditions_array[0];
                                $condition_value = $conditions_array[1];

                                if ($condition == '>=') {
                                    if ($no_answers >= intval($condition_value)) {
                                        $question_score_str .= "" . $questions_set['Question']['question_code'] . "=" . $score . ";";
                                    }
                                } elseif ($condition == '=') {
                                    if ($no_answers == intval($condition_value)) {
                                        $question_score_str .= "" . $questions_set['Question']['question_code'] . "=" . $score . ";";
                                    }
                                }
                            }
                        } else {
                            $question_score_str .= "" . $questions_set['Question']['question_code'] . "=" . $questions_set['Answer'][0]['Answer'][0]['score'] . ";";
                        }
                    } else {
                        $question_score_str .= "" . $questions_set['Question']['question_code'] . "=" . $questions_set['Answer'][0]['Answer'][0]['score'] . ";";
                    }
                }
            }

            $save_str .= $que_grp . '&' . $question_score_str . '||';
        }

        $data['ClientScore'] = array(
            'info_id' => $info_id,
            'question_score' => $save_str
        );

        $this->ClientScore->save($data);

        $this->Session->write('LatestClientScore_id', $this->ClientScore->id);

        //Clear the temp score data for the member
        $t = $this->TempScore->find('first', array(
            'conditions' => array('TempScore.info_id' => $info_id),
            'recursive' => -1
                ));

        $this->TempScore->id = $t['TempScore']['id'];
        $this->TempScore->delete();
        return;
    }

    function statistics() {
        //$this->autoRender = FALSE;

        $this->Session->delete('QuesAns');
        $client_score_set = $this->__get_client_scores_data();
        $client_score_totals = $this->__get_client_scores_totals();
        $info_id = $this->Session->read('Client_id');

        $clientInfo = $this->Info->find('first', array(
            'conditions' => array('Info.id' => $info_id),
        ));


        /** Processing Scores with the rules */
        $msg = array();
        foreach ($client_score_set as $group => $score_arr) {
            $rules = $this->__get_score_rules_data($group);

            /** Applying each rule for the rule group */
            foreach ($rules as $key => $value) {
                $correlates = $value['correlates'];
                $factor = $value['factor'];
                $scenario = $value['scenario'];
                $solution = $value['solution'];

                $count_factor = 0;
                foreach ($correlates as $ques_code) {
                    if ($count_factor == intval($factor)) {
                        break;
                    }
                    if (isset($score_arr[$ques_code])) {
                        if(doubleval($score_arr[$ques_code]) <=4.5){
                            $count_factor++;
                        }
                    }
                }

                if ($count_factor == intval($factor)) {
                    $msg[$group][] = array(
                        'scenario' => $scenario,
                        'solution' => $solution,
                    );
                }
            }
        }

        $p_score_total = isset($client_score_totals['p']) ? round(($client_score_totals['p'] / 247) * 100, 1) : 0;
        $sys_score_total = isset($client_score_totals['sys']) ? round(($client_score_totals['sys'] / 88) * 100, 1) : 0;
        $str_score_total = isset($client_score_totals['str']) ? round(($client_score_totals['str'] / 97) * 100, 1) : 0;
        $firstScoreTotal = $p_score_total + $sys_score_total + $str_score_total;
        $overall_score_total = round(($firstScoreTotal / 300) * 100);

        $pplVcc = $this->__getPeopleVccStatus($p_score_total);
        $systemVcc = $this->__getSystemVccStatus($sys_score_total);
        $strategyVcc = $this->__getStrategyVccStatus($str_score_total);
        $overallVcc = $this->__getOverallVccStatus($overall_score_total);


        $this->setEmailParameters(array(
            'to' => "<" . $clientInfo['Info']['email'] . ">"
        ));


        $this->Email->attachments["Pacem_Diagnostic_Report.pdf"] = $this->Pdf->generate("Pacem_Diagnostic_Report.pdf", '/elements/pdf_statistics', compact('msg', 'client_score_totals', 'clientInfo', 'p_score_total', 'sys_score_total', 'str_score_total', 'pplVcc', 'systemVcc', 'strategyVcc', 'overallVcc', 'overall_score_total')
        );


        if ($this->Email->send()) {

            echo json_encode(array('result' => 'success'));
        } else {
            echo json_encode(array('result' => 'failed', 'error' => $this->Email->smtpError));
        }

        $this->set(compact('msg', 'client_score_totals', 'clientInfo', 'p_score_total', 'sys_score_total', 'str_score_total', 'pplVcc', 'systemVcc', 'strategyVcc', 'overallVcc', 'overall_score_total'));
    }

    private function configureSMTP() {
        /* SMTP Options */
        $this->Email->smtpOptions = array(
            'port' => Configure::read('smtp_port'),
            'timeout' => Configure::read('smtp_timeout'),
            'host' => Configure::read('smtp_host'),
            'username' => Configure::read('smtp_username'),
            'password' => Configure::read('smtp_password'),
        );

        /* Set delivery method */
        $this->Email->delivery = 'smtp';
    }

    public function setEmailParameters($params = array()) {

        $this->configureSMTP();

        $default = array(
            'from' => 'RtHE Consult Limited <PACEM@rtheconsult.com>',
            'to' => array('RtHE Consult Limited <PACEM@rtheconsult.com>'),
            'cc' => array(),
            'bcc' => array(),
            'subject' => 'Pacem Diagnostics Report',
            'replyTo' => 'RtHE Consult Limited <PACEM@rtheconsult.com>',
            'message' => 'Dear Sir/Madam,<br/><br/>
                          Please find attached your PACEM Diagnostics report<br/><br/>
                          Kindly call us so we can discuss your report and we look forward to assisting you in <br/>
                          taking your organisation to greater heights.<br/><br/>
                          Thank you.<br/><br/>
                          RtHE Consult Ltd.<br/><br/>'
        );

        $params = array_merge($default, $params);

        function checkAddressFormat($addresses) {
            if (is_string($addresses)) {
                $addresses = explode(",", $addresses);
            }

            $formatted = array();
            if (is_array($addresses)) {
                foreach ($addresses as $address) {
                    if (strstr($address, "<") && strstr($address, ">")) {
                        $formatted[] = $address;
                    } else {
                        $formatted[] = "$address <$address>";
                    }
                }
            }

            return $formatted;
        }

        $this->Email->to = checkAddressFormat($params['to']);
        $this->Email->cc = checkAddressFormat($params['cc']);
        $this->Email->bcc = checkAddressFormat($params['bcc']);
        $this->Email->subject = $params['subject'];
        $this->Email->replyTo = $params['replyTo'];
        $this->Email->from = $params['from'];

        //Send as 'html', 'text' or 'both' (default is 'text')
        $this->Email->sendAs = 'both'; // because we like to send pretty mail
        $this->Email->template = "empty_message";

        $this->set('message', $params['message']);
    }

    function __get_client_scores_data() {
        $info_id = $this->Session->read('Client_id');
        $lastClientScore_id = $this->Session->read('LatestClientScore_id');
        echo $lastClientScore_id;

        $client_score_data = $this->ClientScore->find('first', array(
            'fields' => array('ClientScore.id', 'ClientScore.question_score'),
            'conditions' => array('ClientScore.info_id' => $info_id, 'ClientScore.id' => $lastClientScore_id),
            'recursive' => -1
                ));

        $score_group_set_str = $client_score_data['ClientScore']['question_score'];

        //p&p1=5;p2=5;p3=5;p12=4;  ||sys&sys2=3.5;sys3=5;sys11=3.5;||str&str5=3.5;str6=5;str9=3.5;str12=3;||

        $client_score_set = array();
        $score_group_set_arr = explode('||', $score_group_set_str);
        foreach ($score_group_set_arr as $key => $value) {
            if ($value) {
                $score_group_arr = explode('&', $value);
                $group = $score_group_arr[0];
                $score_set_str = $score_group_arr[1];
                $quescode_score_arr = explode(';', $score_set_str);
                $scoring = array();
                foreach ($quescode_score_arr as $key1 => $value1) {
                    if ($value1) {
                        $ques_c_mark_arr = explode('=', $value1);
                        $code = $ques_c_mark_arr[0];
                        $mark = $ques_c_mark_arr[1];
                        $scoring[$code] = $mark;
                    }
                }
                $client_score_set[$group] = $scoring;
            }
        }

        return $client_score_set;
    }

    function __get_client_scores_totals() {
        $info_id = $this->Session->read('Client_id');
        $lastClientScore_id = $this->Session->read('LatestClientScore_id');

        $client_score_data = $this->ClientScore->find('first', array(
            'fields' => array('ClientScore.id', 'ClientScore.question_score'),
            'conditions' => array('ClientScore.info_id' => $info_id, 'ClientScore.id' => $lastClientScore_id),
            'recursive' => -1
                ));

        $score_group_set_str = $client_score_data['ClientScore']['question_score'];

        //p&p1=5;p2=5;p3=5;p12=4;  ||sys&sys2=3.5;sys3=5;sys11=3.5;||str&str5=3.5;str6=5;str9=3.5;str12=3;||

        $client_score_set = array();
        $score_group_set_arr = explode('||', $score_group_set_str);
        foreach ($score_group_set_arr as $key => $value) {
            if ($value) {
                $score_group_arr = explode('&', $value);
                $group = $score_group_arr[0];
                $score_set_str = $score_group_arr[1];
                $quescode_score_arr = explode(';', $score_set_str);
                $scoring = 0;
                foreach ($quescode_score_arr as $key1 => $value1) {
                    if ($value1) {
                        $ques_c_mark_arr = explode('=', $value1);
                        $code = $ques_c_mark_arr[0];
                        $mark = $ques_c_mark_arr[1];

                        $scoring += $mark;
                    }
                }
                $client_score_set[$group] = $scoring;
            }
        }

        return $client_score_set;
    }

    function __get_score_rules_data($id) {
        $data = array(
            'p' => array(
                0 => array(
                    'correlates' => array('p5', 'p6'),
                    'factor' => '2',
                    'scenario' => 'Vision, mission, values and culture apathy (i.e. core essence apathy) exists. The likelihood that current and future plans will translate into desired goals is negligible.',
                    'solution' => 'Core essence realignment and recruiting system revamping are needed.'
                ),
                1 => array(
                    'correlates' => array('p5', 'p3', 'p2'),
                    'factor' => '2',
                    'scenario' => 'The core essence of the company isnt passed on to new employees at on-boarding. Their effectiveness is compromised from the start as they respond to whatever agenda presented to them.',
                    'solution' => 'Core essence realignment and recruiting system revamping are needed.'
                ),
                2 => array(
                    'correlates' => array('p9', 'p12', 'p2', 'p3'),
                    'factor' => '2',
                    'scenario' => 'The absence of the VMV/Culture complex leaves team members with no sense of higher purpose on the job. Employees question the game i.e. their jobs as team leaders do not walk the talk and needed work elements and or environment are absent. Overall the company staff are highly demoralised.',
                    'solution' => 'A combination of organisational trend analysis (survey), Core essence realignment and Staff morale boosting sessions are needed.'
                ),
                3 => array(
                    'correlates' => array('p12', 'p6', 'p4'),
                    'factor' => '2',
                    'scenario' => 'Lack of commitment to and non-compliance to the company core essence leads to self interest as opposed to organisational goals. The absence of needed work elements gives employees excuses for underperformance and worsens organisational output. This situation is worsened by the lack of genuine concern management shows for staff.',
                    'solution' => 'A combination of organisational trend analysis (survey), Core essence realignment, Staff morale boosting sessions, and Managers people skills improvement sessions are needed.'
                ),
                4 => array(
                    'correlates' => array('p18', 'p15', 'p11'),
                    'factor' => '2',
                    'scenario' => 'The lack of genuine concern by management for staff issues and its high handed manner in dealing with staff often reflected in the style of communication, represents a catalyst for staff attrition. ',
                    'solution' => 'A combination of organisational trend analysis (survey), Staff morale boosting sessions, and Managers people skills improvement sessions are needed.'
                ),
                5 => array(
                    'correlates' => array('p14', 'p16', 'p18'),
                    'factor' => '2',
                    'scenario' => 'The lack of genuine concern by management for staff issues is often reflected in poor communication, and negligible follow up of staff after trainings. This leads to limited training impact, below par performance despite money invested.',
                    'solution' => 'A combination of organisational trend analysis (survey), Managers people skills improvement sessions, Leadership alignment, and Systematisation training/consulting are needed.'
                ),
                6 => array(
                    'correlates' => array('p17', 'p21', 'p22'),
                    'factor' => '2',
                    'scenario' => 'An arms length approach to managing team members by managers as reflected in their communication style is a symptom of limited/negligible coaching of subordinates. Coupled with limited training effectiveness staff add less value to the business affecting the whole company output and profitability. ',
                    'solution' => 'A combination of organisational trend analysis (survey), Managers people skills improvement sessions, Leadership and talent alignment, and Systematisation training/consulting are needed.'
                ),
                7 => array(
                    'correlates' => array('p21', 'p18', 'p16', 'p14', 'p12'),
                    'factor' => '3',
                    'scenario' => 'The company has not done enough in the areas of resources provision, training and development and this situation leads to below par staff output and lower than expected company performance.',
                    'solution' => 'A combination of organisational trend analysis (survey), Managers people skills improvement sessions, Leadership and talent alignment, and Strategic management realignment training/consulting are needed.'
                ),
                8 => array(
                    'correlates' => array('p12', 'p13', 'p15'),
                    'factor' => '2',
                    'scenario' => 'Multiple causes/reasons for poor staff morale and limited interventions by Management beyond salary payments leads to limited appreciation of any recognition scheme. Employees view management attempts as duplicitous.',
                    'solution' => 'A combination of organisational trend analysis (survey), Staff morale & emotional intelligence boosting sessions, and employee recognition alignment training/consulting are needed.'
                ),
                9 => array(
                    'correlates' => array('p6', 'p17', 'p25', '26'),
                    'factor' => '2',
                    'scenario' => 'Poor employee performance is tied to working tools and environment handicaps which are accentuated by low employee commitment. Limited management intervention leads to overall organisational ineffectiveness. The organisation is quick to hold people accountable but the core essence twist leads to a blame culture.',
                    'solution' => 'A combination of organisational trend analysis (survey), procedural gap analysis, Staff morale & emotional intelligence boosting sessions, and Leadership and talent alignment, and Strategic management realignment training/consulting are needed.'
                ),
                10 => array(
                    'correlates' => array('p16', 'p34', 'p18', 'p22', 'p24', 'p28'),
                    'factor' => '3',
                    'scenario' => 'Poor communication between boss and subordinate leads to limited understanding of the subordinates challenges. Compounding this is the absence of intervention in dealing with skill gaps by the manager. Overall there is a steady decline in employee performance and the manager fails to acknowledge that he/she can change the situation and in most cases blame the employee.',
                    'solution' => 'A combination of organisational trend analysis (survey), Staff morale & emotional intelligence boosting sessions, Leadership and talent alignment, and employee recognition alignment training/consulting are needed.'
                ),
            ),
            'sys' => array(
                0 => array(
                    'correlates' => array('sys1', 'sys2', 'sys3', 'sys5'),
                    'factor' => '2',
                    'scenario' => 'The absence of documented processes, procedures and systems coupled with training and innovation issues, will lead to overall inefficiency with average to declining business results.',
                    'solution' => 'Systematisation realignment and entrenchment, Procedural gap analysis and procedures systems development,Strategic management realignment training/consulting are needed.'
                ),
                1 => array(
                    'correlates' => array('sys4', 'sys5', 'sys3'),
                    'factor' => '2',
                    'scenario' => 'The results show a system that isnt structured to meet the company challenges but worse still, the results imply that the management team is taking no steps to rectify the situation.',
                    'solution' => 'Organisational trend analysis (survey), System realignment and system thinking entrenchment, Procedural gap analysis and procedures systems development,Strategic management realignment training/consulting are needed.'
                ),
                2 => array(
                    'correlates' => array('sys4', 'sys5', 'sys6', 'sys9', 'sys7'),
                    'factor' => '3',
                    'scenario' => 'Inconsistent business systems, negligible or absent audit functions, etc., are all reflective of a skewed organisation structure.',
                    'solution' => 'Organisational trend analysis (survey), System realignment and system thinking entrenchment, Procedural gap analysis and procedures systems development,Strategic management realignment training/consulting are needed.'
                ),
                3 => array(
                    'correlates' => array('sys8', 'sys2', 'sys3', 'sys7'),
                    'factor' => '2',
                    'scenario' => 'Managers are the hub of business development. Low spend on innovation and undocumented or dysfunctional systems and procedures holding sway in the company are a reflections of managers failing to play their role.',
                    'solution' => 'Organisational trend analysis (survey), System realignment and system thinking entrenchment, Procedural gap analysis and procedures systems development,Strategic management realignment training/consulting are needed.'
                )
            ),
            'str' => array(
                0 => array(
                    'correlates' => array('str2', 'str3', 'str1', 'str7'),
                    'factor' => '2',
                    'scenario' => 'The company lacks a functional strategic document and staff are unclear about the strategic direction of the company and cannot play their roles effectively. Strategy reviews and realignment along with tapping in on strategic innovation from all levels of the company are absent. Overall the company is on a strategic mission with no strategy map and no strategy navigators.',
                    'solution' => 'Strategic management realignment (including strategic techniques workshop) training/consulting including Strategy Hub System development are needed.'
                ),
                1 => array(
                    'correlates' => array('str9', 'str7', 'str3', 'str5'),
                    'factor' => '2',
                    'scenario' => 'The company has not invested in strategic learning and techniques and strategic discussions are not taking place as the leadership focus is skewed towards money creation rather than value creation. ',
                    'solution' => 'Strategic management realignment (including strategic techniques workshop) training/consulting including Strategy Hub System development are needed.'
                ),
                2 => array(
                    'correlates' => array('str9', 'str3', 'str4', 'str8', 'str13'),
                    'factor' => '3',
                    'scenario' => 'Strategic decisions are the purview of a few and the imperative for deep analysis in this type of situation is often shelved. ',
                    'solution' => 'Strategic management realignment (including strategic techniques workshop) training/consulting including Strategy Hub System development are needed.'
                ),
                3 => array(
                    'correlates' => array('str3', 'str6', 'str14'),
                    'factor' => '2',
                    'scenario' => 'Employees are not engaged in strategic decision making, or other activities that will develop their strategic IQ. Worst still, employees lack strategic objectives in their targets and cannot directly contribute to the core strategic direction of the company.',
                    'solution' => 'Managers people skills improvement sessions, Strategic management techniques workshop and Strategy cascading to teams training are needed.'
                )
            )
        );

        return $data[$id];
    }
    
    /**
     * Get PACEM Long Report
     */
    function __get_full_score_rules_data($id) {
        $data = array(
            'p' => array(
                0 => array(
                    'correlates' => array('p5', 'p6'),
                    'factor' => '2',
                    'scenario' => 'Vision, mission, values and culture apathy (i.e. core essence apathy) exists. The likelihood that current and future plans will translate into desired goals is negligible.',
                    'solution' => 'Core essence realignment and recruiting system revamping are needed.'
                ),
                1 => array(
                    'correlates' => array('p5', 'p3', 'p2'),
                    'factor' => '2',
                    'scenario' => 'The core essence of the company isnt passed on to new employees at on-boarding. Their effectiveness is compromised from the start as they respond to whatever agenda presented to them.',
                    'solution' => 'Core essence realignment and recruiting system revamping are needed.'
                ),
                2 => array(
                    'correlates' => array('p9', 'p12', 'p2', 'p3'),
                    'factor' => '2',
                    'scenario' => 'The absence of the VMV/Culture complex leaves team members with no sense of higher purpose on the job. Employees question the game i.e. their jobs as team leaders do not walk the talk and needed work elements and or environment are absent. Overall the company staff are highly demoralised.',
                    'solution' => 'A combination of organisational trend analysis (survey), Core essence realignment and Staff morale boosting sessions are needed.'
                ),
                3 => array(
                    'correlates' => array('p12', 'p6', 'p4'),
                    'factor' => '2',
                    'scenario' => 'Lack of commitment to and non-compliance to the company core essence leads to self interest as opposed to organisational goals. The absence of needed work elements gives employees excuses for underperformance and worsens organisational output. This situation is worsened by the lack of genuine concern management shows for staff.',
                    'solution' => 'A combination of organisational trend analysis (survey), Core essence realignment, Staff morale boosting sessions, and Managers people skills improvement sessions are needed.'
                ),
                4 => array(
                    'correlates' => array('p18', 'p15', 'p11'),
                    'factor' => '2',
                    'scenario' => 'The lack of genuine concern by management for staff issues and its high handed manner in dealing with staff often reflected in the style of communication, represents a catalyst for staff attrition. ',
                    'solution' => 'A combination of organisational trend analysis (survey), Staff morale boosting sessions, and Managers people skills improvement sessions are needed.'
                ),
                5 => array(
                    'correlates' => array('p14', 'p16', 'p18'),
                    'factor' => '2',
                    'scenario' => 'The lack of genuine concern by management for staff issues is often reflected in poor communication, and negligible follow up of staff after trainings. This leads to limited training impact, below par performance despite money invested.',
                    'solution' => 'A combination of organisational trend analysis (survey), Managers people skills improvement sessions, Leadership alignment, and Systematisation training/consulting are needed.'
                ),
                6 => array(
                    'correlates' => array('p17', 'p21', 'p22'),
                    'factor' => '2',
                    'scenario' => 'An arms length approach to managing team members by managers as reflected in their communication style is a symptom of limited/negligible coaching of subordinates. Coupled with limited training effectiveness staff add less value to the business affecting the whole company output and profitability. ',
                    'solution' => 'A combination of organisational trend analysis (survey), Managers people skills improvement sessions, Leadership and talent alignment, and Systematisation training/consulting are needed.'
                ),
                7 => array(
                    'correlates' => array('p21', 'p18', 'p16', 'p14', 'p12'),
                    'factor' => '3',
                    'scenario' => 'The company has not done enough in the areas of resources provision, training and development and this situation leads to below par staff output and lower than expected company performance.',
                    'solution' => 'A combination of organisational trend analysis (survey), Managers people skills improvement sessions, Leadership and talent alignment, and Strategic management realignment training/consulting are needed.'
                ),
                8 => array(
                    'correlates' => array('p12', 'p13', 'p15'),
                    'factor' => '2',
                    'scenario' => 'Multiple causes/reasons for poor staff morale and limited interventions by Management beyond salary payments leads to limited appreciation of any recognition scheme. Employees view management attempts as duplicitous.',
                    'solution' => 'A combination of organisational trend analysis (survey), Staff morale & emotional intelligence boosting sessions, and employee recognition alignment training/consulting are needed.'
                ),
                9 => array(
                    'correlates' => array('p6', 'p17', 'p25', '26'),
                    'factor' => '2',
                    'scenario' => 'Poor employee performance is tied to working tools and environment handicaps which are accentuated by low employee commitment. Limited management intervention leads to overall organisational ineffectiveness. The organisation is quick to hold people accountable but the core essence twist leads to a blame culture.',
                    'solution' => 'A combination of organisational trend analysis (survey), procedural gap analysis, Staff morale & emotional intelligence boosting sessions, and Leadership and talent alignment, and Strategic management realignment training/consulting are needed.'
                ),
                10 => array(
                    'correlates' => array('p16', 'p34', 'p18', 'p22', 'p24', 'p28'),
                    'factor' => '3',
                    'scenario' => 'Poor communication between boss and subordinate leads to limited understanding of the subordinates challenges. Compounding this is the absence of intervention in dealing with skill gaps by the manager. Overall there is a steady decline in employee performance and the manager fails to acknowledge that he/she can change the situation and in most cases blame the employee.',
                    'solution' => 'A combination of organisational trend analysis (survey), Staff morale & emotional intelligence boosting sessions, Leadership and talent alignment, and employee recognition alignment training/consulting are needed.'
                ),
            ),
            'sys' => array(
                0 => array(
                    'correlates' => array('sys1', 'sys2', 'sys3', 'sys5'),
                    'factor' => '2',
                    'scenario' => 'The absence of documented processes, procedures and systems coupled with training and innovation issues, will lead to overall inefficiency with average to declining business results.',
                    'solution' => 'Systematisation realignment and entrenchment, Procedural gap analysis and procedures systems development,Strategic management realignment training/consulting are needed.'
                ),
                1 => array(
                    'correlates' => array('sys4', 'sys5', 'sys3'),
                    'factor' => '2',
                    'scenario' => 'The results show a system that isnt structured to meet the company challenges but worse still, the results imply that the management team is taking no steps to rectify the situation.',
                    'solution' => 'Organisational trend analysis (survey), System realignment and system thinking entrenchment, Procedural gap analysis and procedures systems development,Strategic management realignment training/consulting are needed.'
                ),
                2 => array(
                    'correlates' => array('sys4', 'sys5', 'sys6', 'sys9', 'sys7'),
                    'factor' => '3',
                    'scenario' => 'Inconsistent business systems, negligible or absent audit functions, etc., are all reflective of a skewed organisation structure.',
                    'solution' => 'Organisational trend analysis (survey), System realignment and system thinking entrenchment, Procedural gap analysis and procedures systems development,Strategic management realignment training/consulting are needed.'
                ),
                3 => array(
                    'correlates' => array('sys8', 'sys2', 'sys3', 'sys7'),
                    'factor' => '2',
                    'scenario' => 'Managers are the hub of business development. Low spend on innovation and undocumented or dysfunctional systems and procedures holding sway in the company are a reflections of managers failing to play their role.',
                    'solution' => 'Organisational trend analysis (survey), System realignment and system thinking entrenchment, Procedural gap analysis and procedures systems development,Strategic management realignment training/consulting are needed.'
                )
            ),
            'str' => array(
                0 => array(
                    'correlates' => array('str2', 'str3', 'str1', 'str7'),
                    'factor' => '2',
                    'scenario' => 'The company lacks a functional strategic document and staff are unclear about the strategic direction of the company and cannot play their roles effectively. Strategy reviews and realignment along with tapping in on strategic innovation from all levels of the company are absent. Overall the company is on a strategic mission with no strategy map and no strategy navigators.',
                    'solution' => 'Strategic management realignment (including strategic techniques workshop) training/consulting including Strategy Hub System development are needed.'
                ),
                1 => array(
                    'correlates' => array('str9', 'str7', 'str3', 'str5'),
                    'factor' => '2',
                    'scenario' => 'The company has not invested in strategic learning and techniques and strategic discussions are not taking place as the leadership focus is skewed towards money creation rather than value creation. ',
                    'solution' => 'Strategic management realignment (including strategic techniques workshop) training/consulting including Strategy Hub System development are needed.'
                ),
                2 => array(
                    'correlates' => array('str9', 'str3', 'str4', 'str8', 'str13'),
                    'factor' => '3',
                    'scenario' => 'Strategic decisions are the purview of a few and the imperative for deep analysis in this type of situation is often shelved. ',
                    'solution' => 'Strategic management realignment (including strategic techniques workshop) training/consulting including Strategy Hub System development are needed.'
                ),
                3 => array(
                    'correlates' => array('str3', 'str6', 'str14'),
                    'factor' => '2',
                    'scenario' => 'Employees are not engaged in strategic decision making, or other activities that will develop their strategic IQ. Worst still, employees lack strategic objectives in their targets and cannot directly contribute to the core strategic direction of the company.',
                    'solution' => 'Managers people skills improvement sessions, Strategic management techniques workshop and Strategy cascading to teams training are needed.'
                )
            )
        );

        return $data[$id];
    }
    

    function __getPeopleVccStatus($score =0) {
        $action = $score;
        $pplResult = "";
        if ($action >= 0 && $action <= 50) {
            $pplResult = 'Your VCC level indicates very poor employee engagement, coupled with low output
                          and possible impropriety in its various forms coupled with high staff turnover
                          and the need significant culture change on all organisational levels.';
        } elseif ($action >= 51 && $action <= 65) {
            $pplResult = 'Your VCC level indicates that employee engagement and output are low/average and
                          possibly low accountability and noticeable staff turnover. Major culture change
                          required on most organisational levels.';
        } elseif ($action >= 66 && $action <= 75) {
            $pplResult = 'Your VCC level indicates that there is good/strong employee engagement and output
                          but possibly low empowerment and staff attrition tied to leadership issues.
                          Targeted culture changes required in key areas of the organisation.';
        } elseif ($action >= 76 && $action <= 85) {
            $pplResult = 'Your VCC level indicates that limited culture changes required. Indications are
                          that there is good employee empowerment, better accountability and leadership
                          coupled with lower levels of attrition. Challenges in recognition and talent
                          management may exist.';
        } elseif ($action >= 86 && $action <= 95) {
            $pplResult = 'Your VCC level indicates that negligible changes are required - focus should
                          be on culture consolidation, talent retention and succession planning.';
        } elseif ($action >= 96 && $action <= 100) {
            $pplResult = 'Your VCC level indicates that negligible changes are required - focus should
                          be on culture consolidation, and the leadership pipeline.';
        }
        return $pplResult;
    }

    function __getSystemVccStatus($score =0) {
        $action = $score;
        $sysResult = "";
        if ($action >= 0 && $action <= 50) {
            $sysResult = 'Your VCC level indicates that systems efficiency and effectiveness are compromised
                          and future efforts will most probably not yield desired results. Significant systems
                          changes are required at all organisational levels.';
        } elseif ($action >= 51 && $action <= 65) {
            $sysResult = 'Your VCC level indicates that systems efficiency and effectiveness are low/average
                          and future efforts will most probably not yield consistent results. Major systems
                          changes are required at most organisational levels.';
        } elseif ($action >= 66 && $action <= 75) {
            $sysResult = 'Your VCC level indicates that systems efficiency and effectivenessare good/strong
                          and future system use and output will probably yield mixed results. Targeted systems
                          changes are required in key areas of the organisation.';
        } elseif ($action >= 76 && $action <= 85) {
            $sysResult = 'Your VCC level indicates that systems efficiency and effectiveness are high and future
                          system use and output will probably yield desired results in a consistent manner. Limited
                          systems changes are required but keen focus should be on compliance and innovation.';
        } elseif ($action >= 86 && $action <= 95) {
            $sysResult = 'Your VCC level indicates that systems efficiency and effectiveness are very
                          high coupled with a strong systems compliance culture. Future system output will yield
                          desired results in a consistent manner – negligible systems changes are required with
                          focus on innovation and new business imperatives.';
        } elseif ($action >= 96 && $action <= 100) {
            $sysResult = 'Your VCC level indicates that systems efficiency and effectiveness are top notch coupled
                          with a strong systems compliance and innovation culture. Future system output will yield
                          desired results in a consistent manner. Systems changes should focus on new business
                          imperatives.';
        }
        return $sysResult;
    }

    function __getStrategyVccStatus($score =0) {
        $strResult = "";
        $action = $score;
        if ($action >= 0 && $action <= 50) {
            $strResult = 'Your VCC level indicates that strategic direction and focus is poor limiting the chances
                          of achieving the organisation mission and set goals. A totally new approach to
                          strategic management starting with strategic planning is required if the organisation
                          is to survive.';
        } elseif ($action >= 51 && $action <= 65) {
            $strResult = 'Your VCC level indicates that strategic direction and focus is average at
                          best and the organisation’s ability to achieve its set goals and effectively compete is
                          compromised. A totally new approach to strategic management is required if the
                          organisation to improve its performance.';
        } elseif ($action >= 66 && $action <= 75) {
            $strResult = 'Your VCC level indicates that strategic direction and focus is good/strong but the
                          execution of strategic imperatives and the capacity to strategically compete still
                          does not meet set expectations. Entrenchment of strategic management thinking across
                          the organisation will lead to significant performance improvements.';
        } elseif ($action >= 76 && $action <= 85) {
            $strResult = 'Your VCC level indicates that strategic direction and management are very
                          good yet execution of strategic imperatives still gives mixed results. Better
                          application of strategic management and realignment in key units will lead to
                          significant improvements in organisational performance.';
        } elseif ($action >= 86 && $action <= 95) {
            $strResult = 'Your VCC level indicates that strategic management and strategic realignment
                          are very good and execution of strategic imperatives gives strong results. Better
                          cohesion and application of strategic realignment in key units will lead to even
                          better performance.';
        } elseif ($action >= 96 && $action <= 100) {
            $strResult = 'Your VCC level indicates that the total approach to strategic issues is laudable
                          and execution of strategic imperatives gives results that lead to significant
                          competitive advantage. Focus should be on strategic realignment taking cognisance
                          of the business environment.';
        }
        return $strResult;
    }

    function __getOverallVccStatus($score =0) {
        $overallResult = "";
        $action = $score;
        if ($action >= 0 && $action <= 50) {
            $overallResult = 'Your VCC level indicates that future performance results and market position are
                              not assured and the need for significant change on all organisational levels.';
        } elseif ($action >= 51 && $action <= 65) {
            $overallResult = 'Your VCC level indicates that future performance results will fluctuate and market
                              position at best will be static hence the need for major changes on most organisational
                              levels.';
        } elseif ($action >= 66 && $action <= 75) {
            $overallResult = 'Your VCC level indicates that future performance results will hold strong but
                              market position at best will be grow marginally. It indicates the need for targeted
                              changes in key areas of the organisation.';
        } elseif ($action >= 76 && $action <= 85) {
            $overallResult = 'Your VCC level indicates that future performance results will hold strong and market
                              position will experience significant growth. Yet your level implies the need for
                              targeted changes (with greater focus on customer satisfaction and innovation)
                              in key areas of the organisation.';
        } elseif ($action >= 86 && $action <= 95) {
            $overallResult = 'Your VCC level indicates that future performance results are guaranteed with
                              significant growth achievements and top-tier market position/leadership status
                              possibilities. Your scores indicate that negligible changes are required- focus
                              is on consolidation and greater innovation.';
        } elseif ($action >= 96 && $action <= 100) {
            $overallResult = 'Your VCC level indicates that future performance results are guaranteed with
                              significant growth achievements and market leadership or niche status possibilities.
                              Your scores indicate that negligible changes are required - focus should be on
                              consolidation and innovation.';
        }
        return $overallResult;
    }

    function thankYou() {
        
    }

    function people() {
        
    }

    function system() {
        
    }

    function strategy() {
        
    }

    function personalInfo() {
        $info_id = $this->Session->read('Client_id'); 
        if (!empty($this->data)) {
            $this->BioData->create();
            if ($this->BioData->save($this->data)) {
                $this->redirect(array('controller' => 'Questions', 'action' => 'thankYou'));
            } elseif ($this->data == "") {
                $this->Session->setFlash('Bio Data not saved. Try again.');
            }
        }
        
        $this->set(compact('info_id'));
    }
    
    
   // function get

}

?>